import React from 'react';
import { Button, Form } from 'antd';
import { recheckWhenError } from '@/utils/formHelper';
import QuestionFormItem, { ITEM_MODE } from './QuestionFormItem';

const fieldName = 'tempQuestions';
const submitCheckFiledName = `${fieldName}SubmitCheck`;
const questionLabel = 'question';
const editingLabel = 'editing';
const getChildFiledName = (index, child) => `${fieldName}[${index}].${child}`;

const noop = () => {};
/**
 * 适用数据格式: {...rest,[fieldName]:{id:xxx,question:xxx,createUserName:xxx,disabled:Boolean,other:Boolean,editing:Boolean}} 只会修改editing 和 question的值
 * @param {*} param0
 */
function QuestionListFormItem({ form, disabled, value, onChange = noop, ...rest }, ref) {
    const { getFieldDecorator } = form;

    const handleConfirm = React.useCallback(
        (index, val) => {
            const nextValue = [...value];
            const targetItem = nextValue[index];
            nextValue.splice(index, 1, {
                ...targetItem,
                [questionLabel]: val
            });
            onChange(nextValue);
        },
        [onChange, value]
    );

    const handleRemove = React.useCallback(
        index => {
            const nextValue = value.filter((_, i) => i !== index);
            onChange(nextValue);
            recheckWhenError(form, submitCheckFiledName);
        },
        [onChange, value]
    );

    const handleModeChange = React.useCallback(
        (index, nextMode) => {
            const nextValue = [...value];
            const targetItem = nextValue[index];
            nextValue.splice(index, 1, { ...targetItem, [editingLabel]: nextMode === ITEM_MODE.EDITING });
            onChange(nextValue);
            recheckWhenError(form, submitCheckFiledName);
        },
        [onChange, value]
    );

    const handleAdd = React.useCallback(() => {
        const nextValue = [...value, { editing: true }];
        onChange(nextValue);
    }, [onChange, value]);

    const renderFormItem = (item, index) => {
        const { question, editing, other, createUserName } = item || {};

        const itemStyle = index !== 0 ? { marginTop: 8 } : {};

        const renderSuffix = () => {
            if (other) {
                return <span style={{ marginLeft: 16 }}>{createUserName}</span>;
            }
            return null;
        };
        return (
            <QuestionFormItem
                style={itemStyle}
                key={index}
                form={form}
                fieldDecoratorId={getChildFiledName(index, questionLabel)}
                fieldDecoratorOptions={{
                    initialValue: question,
                    rules: [
                        {
                            required: true,
                            message: '请输入自定义问题标题!'
                        },
                        {
                            max: 100,
                            message: '自定义问题不能超过100个字符'
                        }
                    ]
                }}
                initMode={editing ? ITEM_MODE.EDITING : ITEM_MODE.BROWSING}
                onModeChange={nextMode => handleModeChange(index, nextMode)}
                onRemove={() => handleRemove(index)}
                onConfirm={val => handleConfirm(index, val)}
                disabled={disabled || other}
                suffix={renderSuffix()}
                questionNumber={index + 1}
            />
        );
    };

    return (
        <div {...rest} ref={ref}>
            <Form.Item style={{ marginBottom: 0, lineHeight: 1.5 }}>
                {getFieldDecorator(submitCheckFiledName, {
                    validateTrigger: '',
                    rules: [
                        {
                            validator(_, foo, callback) {
                                const editing = value.some(item => !!item?.[editingLabel]);
                                if (editing) {
                                    callback('请完成自定义问题编辑！');
                                    return;
                                }
                                callback();
                            }
                        }
                    ]
                })(<div>{value?.map(renderFormItem)}</div>)}
            </Form.Item>
            {!disabled && (
                <Button
                    type="dashed"
                    style={{
                        width: '100%',
                        marginTop: 8
                    }}
                    onClick={handleAdd}
                >
                    + 添加
                </Button>
            )}
        </div>
    );
}
export default React.forwardRef(QuestionListFormItem);
